<?php

namespace app\home\controller;


use app\BaseController;
use think\facade\Db;
use utils\wechart\PayService;
use utils\weixinpay\wechatpay;
use wxcode\qrcode;
require_once '../extend/phpQuery/phpQuery.php';
class Index extends BaseController
{
	
	//首页
	public function index(){

        $list = Db::name('mbti')
            ->where('extension',1)
            ->order('mbti_id desc')
            ->limit(2)
            ->select();
        $this->view->assign('list',$list);
		return view('index');
	}
	
	public function test()
    {
        $id = $this->request->param('id');
        if(!is_numeric($id)){
            return $this->error('没有找到资源');
        }
        $arr = Db::name('mbti')
            ->where('extension',1)
            ->order('mbti_id desc')
            ->limit(2)
            ->column('mbti_id');
        if(!in_array($id,$arr)){
            return $this->error('没有找到资源');
        }

        $mbti = Db::name('mbti')->where('mbti_id',$id)->find();
        $mbti_subject = Db::name('mbti_subject')
            ->where('mbti_id',$mbti['mbti_id'])
            ->select()->toArray();
        if(empty($mbti_subject)){
            return $this->error('没有找到资源');
        }
        $arr = [];
        $data = [1=>['title'=>'词对题','arr'=>[]],2=>['title'=>'描述题','arr'=>[]],3=>['title'=>'验证题','arr'=>[]],4=>['title'=>'终测题','arr'=>[]]];
        foreach ($mbti_subject as $v){
            $v['options'] = explode(',_',$v['options']);
            $v['fraction'] = explode(',_',$v['fraction']);
            $v['choice'] = '';
            $v['how'] = '';
            $arr[$v['type']][] = $v;
        }
        ksort($arr);
        $json = [];
        $data[1]['count'] = count($arr[1]);
        $data[2]['count'] = count($arr[2]);
        $data[3]['count'] = count($arr[3]);
        $data[4]['count'] = count($arr[4]);
        $json = array_merge($arr[1],$arr[2],$arr[3],$arr[4]);
        $this->view->assign('mbti_id',$id);
        $this->view->assign('data',$data);
        $this->view->assign('json',$json);
        return view('test');
    }

    public function testSuccess()
    {
        $post = $this->request->post('data');
        $mbti_id = $this->request->post('id');
        $data = [];
        foreach ($post as $v){
            $data[$v['subject_id']]['choice'] = $v['choice'];
            $data[$v['subject_id']]['how'] = $v['how'];
        }
        $res = mbit_calculation($data);
        $json = json_encode($data);

        $mbti = Db::name('mbti')->where('mbti_id',$mbti_id)->find();


        $order =doOrderSn('DSS');
        $data = [];
        $data['order_son'] = $order;
        $data['title'] = $mbti['title'];
        $data['price'] = $mbti['price'];
        $data['money'] = $mbti['money'];
        $data['pay_type'] = '1';
        $data['state'] = '0';
        $data['create_time'] = time();
        $data['outcome_json'] = $json;
        $data['outcome'] = $res;
        $data['mbti_id'] = $mbti_id;
        $o = Db::name('order')->insert($data);
        if($o){
            return $this->success('提交成功',url('outcome',['order_no'=>$order]));
        }else{
            return $this->error('失败');
        }
    }
    //支付页
    public function outcome()
    {
        $order_no = $this->request->param('order_no');
        $order = Db::name('order')->where('order_son',$order_no)->find();
        if(empty($order)){
            $this->error('未找到订单号');
        }
        if($order['state'] == 1){
          return  redirect("complete?order_no={$order_no}");
        }

        $mbti = Db::name('mbti')->where('mbti_id',$order['mbti_id'])->find();

        $this->view->assign('order_no',$order_no);
        $this->view->assign('mbti',$mbti);
        $this->view->assign('order',$order);
        return view('pay');
    }
    //微信支付
    public function wxpay()
    {
        $order_no = $this->request->param('order_no');
        $state = $this->request->param('state');
        $order = Db::name('order')->where('order_son',$order_no)->find();
        if(empty($order)){
            $this->error('未找到订单号');
        }
        if($state == 1){//完整版
            $zj_price = bcadd($order['price'],$order['money']);
            $level = 2;
        }else{//基础版
            $zj_price = $order['price'];
            $level = 1;
        }
        Db::name('order')
            ->where('order_son',$order_no)
            ->update(['actual_price'=>$zj_price,'level'=>$level]);
        $wxpay = new wechatpay();
        $order = array(
            'body'         => 'mbit购买',
            'detail'       => 'mbit购买',
            'total_fee'    => '0.01' * 100, //分
            'out_trade_no' => $order_no,
            'trade_type'=>'MWEB'
        );
        $res = $wxpay ->mweb($order);
        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
//            $redirect_uri = 'http://xlcp.redyin.net'.url('outcome');
//            $redirect_uri .= '?order_no=' . $order['out_trade_no'];
            $url = $res['mweb_url'];
//            $url .= '&redirect_url=' . urlencode($redirect_uri);
            echo '<script>window.location.href="' . $url . '"</script>';
        }
    }

    public function complete()
    {
        $order_no = $this->request->param('order_no');
        $qrcode = new qrcode();
        $data = [
            'expire_seconds' =>'604800',
            'action_name' => 'QR_STR_SCENE',
            'action_info' => ['scene'=>['scene_str'=>$order_no]],
        ];
        $qr_code= $qrcode->wxappCode($data);
        $this->view->assign('qr_code',$qr_code);
        return view('complete');
    }
    //成
    public function restatus()
    {
        $order_no = $this->request->param('order_no');
        $state = Db::name('order')->where('order_son',$order_no)->value('state');
        if($state == 1){
            $this->success('成功',url('complete',['order_no'=>$order_no]));
        }else{
            $this->error('失败');
        }
    }



    public function text()
    {
        $qrcode = new qrcode();
        $data = [
            'touser' =>'oXwlZ5iIC3aJoJUO_5Sz2YpcEzKg',
            'msgtype' => 'text',
            'text' => ['content'=>'123'],
        ];
        $qr_code= $qrcode->send($data);
    }

    //h5异步回调
    public function wxnotify()
    {
        // 导入微信支付sdk
        $wxpay  =new wechatpay();
        $result = $wxpay->notify();
//        $result['out_trade_no'] = 'CS151494351797648';
//        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
//        $txt = json_encode($result,true);
//        fwrite($myfile, $txt);
//        fclose($myfile);
        if ($result) {
            // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
            $this->handleOrder($result['out_trade_no'],$result['openid'],$result['transaction_id']);
//$this->success('支付成功', U('order/mlist', array('orderno' =>$result['out_trade_no'])));
        }
    }

    public function handleOrder($order,$openid,$pay_order)
    {
        Db::name('order')->where('order_son',$order)->update([
            'pay_time'=>time(),
            'pay_order'=>$pay_order,
            'openid'=>$openid,
            'state'=>1
        ]);
    }
    //预约回调
    public function about_notify()
    {
        // 导入微信支付sdk
        $wxpay  =new wechatpay();
        $result = $wxpay->notify();
//        $result['out_trade_no'] = 'CS151494351797648';
//        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
//        $txt = json_encode($result,true);
//        fwrite($myfile, $txt);
//        fclose($myfile);
        if ($result) {
            // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
            Db::name('customer_list')->where('order_no',$result['out_trade_no'])->update([
                'pay_time'=>time(),
                'state'=>1,
                'pay_order'=>$result['transaction_id']
            ]);
        }
    }
    //小程序回调
    public function xcx_notify()
    {
        // 导入微信支付sdk
        $wxpay  =new wechatpay();
        $result = $wxpay->notify();
//        $result['out_trade_no'] = 'CS151494351797648';
//        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
//        $txt = json_encode($result,true);
//        fwrite($myfile, $txt);
//        fclose($myfile);
        if ($result) {
            // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
            $order_no = $result['out_trade_no'];//订单号
            $pay_order = $result['transaction_id'];//支付订单号
            $openid = $result['openid'];
            $order_s = Db::name('order_record')
                ->where('sc_order',$order_no)
                ->find();
            //第一次购买
            if($order_s['level'] == 0){
                Db::name('order')->where('order_id',$order_s['o_id'])->update([
                    'pay_time'=>time(),
                    'pay_order'=>$pay_order,
                    'openid'=>$openid,
                    'state'=>1,
                    'level'=>2
                ]);
                if($order_s['type'] == 1){
                    Db::name('users')->where('u_id',$order_s['uid'])->inc('count',3)->update();
                }
            }else if($order_s['level'] == 1){
                Db::name('order')->where('order_id',$order_s['o_id'])->update(['level'=>2]);
                if($order_s['type'] == 1){
                    Db::name('users')->where('u_id',$order_s['uid'])->inc('count',3)->update();
                }
            }else if($order_s['level'] == 2){
                Db::name('users')->where('u_id',$order_s['uid'])->inc('count',3)->update();
            }
            Db::name('order_record')
                ->where('id',$order_s['id'])
                ->update(['pay_order'=>$pay_order,'pay_time'=>time(),'state'=>1]);
        }
    }

    public function zsc()
    {
        $list = Db::name("mbti1")->where("state",1)->select()->toArray();
        foreach($list as $v){
            $arr = [];
            $arr['title'] = $v['title'];
            $arr['mbti_id'] = 3;
            $arr['mt_id'] = $v['status'];
            $arr['option_num'] = 2;
            $r = Db::name("mbti_subject")->insertGetId($arr);



            Db::name("mbti_option")->insert([
                'option_title'=>$v["da1"],
                "factor"=>$v["type1"],
                "subject_id"=>$r,
            ]);
            Db::name("mbti_option")->insert([
                'option_title'=>$v["da2"],
                "factor"=>$v["type2"],
                "subject_id"=>$r,
            ]);
            Db::name("mbti1")->where("mbti_id",$v['mbti_id'])->update(["state"=>2]);
        }

        dump($list);die;
    }

    public function zajax()
    {
        if($this->request->isAjax()){
            $list = Db::name("mbti1")->where("state",0)->find();

            if(empty($list)){
                die;
            }

            return json_encode($list);
        }


        return view("zajax");
    }

    public function posttj()
    {
        $data = $this->request->param();
        $sid = $data["sid"];
        $data["state"] = 1;
        $r = Db::name("mbti1")->where("sid",$sid)->update($data);
        echo $r;
    }


    public function cjces()
    {
        $list = Db::name("mbti_result_copy1")->where("state","0")->select()->toArray();
        dump($list);
        foreach ($list as $v){
            $html =file_get_contents('https://mbti.guoxuejianyi.com/cp68admin.php/exam.result/handle_mbti_result?id='.$v['sid'].'&exam_id=63');

            $doc = \phpQuery::newDocument($html);
            $osu = $doc->find(".content_input");
            $title = $osu->find(".layui-input");
            $count = $title->count();
            $content = $osu->find(".layui-textarea");
            for ($i=0;$i<$count;$i++){
                $titles = $title->eq($i)->attr("value");
                $contents = $content->eq($i)->html();
                Db::name("mbti_complete_copy1")->insert(["title"=>$titles,"content"=>$contents,"result_id"=>$v["result_id"]]);
            }
            Db::name("mbti_result_copy1")->where("result_id",$v["result_id"])->update(["state"=>1,"count"=>$count]);
        }

    }


    public function dsjle()
    {
        $list = Db::name("mbti_result_copy1")->where("state",1)->select()->toArray();
        foreach ($list as $v){
            $rid = Db::name("mbti_result")->insertGetId(["results"=>$v["results"],"mbti_id"=>4]);

            $arr = Db::name("mbti_complete_copy1")->where("result_id",$v["result_id"])->select()->toArray();
            foreach ($arr as $vv){
                Db::name("mbti_complete")->insert([
                    "title"=>$vv["title"],
                    "content"=>$vv["content"],
                    "result_id"=>$rid
                ]);
            }
            Db::name("mbti_result_copy1")->where("result_id",$v["result_id"])->update(["state"=>2]);
        }
    }

}
